import { Component, ElementRef, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { HttpModule, Headers, RequestOptions, Http } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';

import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { addDatatype, institutiondates, roledatas } from '../../institution/institution-add-admin/institution-add-admin.component';
import { roleaddtype } from 'app/user/role/role-add/role-add.component';
import { Data } from '@angular/router/src/config';
import { HintsService } from '../../../public/serve/hints/hints.service';

declare var $: any;

@Component({
  selector: 'app-management-add',
  templateUrl: './management-add.component.html',
})
export class ManagementAddComponent implements OnInit {

  constructor(
    private http: Http, 
    private router: Router, 
    private server: Service, 
    private cudTableService: CudTableService, 
    public activatedRoute: ActivatedRoute,
    private  hintsService: HintsService
  ) {
    this.createUserId = this.server.getuser();
  }

  ngOnInit() {
    //console.log(this.createUserId)
    //首次进入接受tree数据
    this.managementtreeidnameeventEmit = this.server.managementtreeidnameeventEmit.subscribe((value: any) => {
      this.superiorAdd = value.institutionName;
      this.superiorAddId = value.institutionId;
    })
    //最大时间
    this.maxDate = new Date();
  }

  //取消订阅
  public managementtreeidnameeventEmit: any;
  ngOnDestroy() {
    if (this.managementtreeidnameeventEmit) {
      this.managementtreeidnameeventEmit.unsubscribe()
    }
  }

  ngAfterViewInit(): void {

  }


  public maxDate: Data;

  //验证是否选图片
  //public imgActive: string = '';
  ngDoCheck() {
    // if ($("#exampleInputUpload").hasClass("fileinput-exists")) {
    //   this.imgActive = "有图";
    // } else {
    //   this.imgActive = '';
    // }
  }

  ngAfterContentInit() {
    this.getTabList();
  }

  public managementtime: any;
  @Output()
  addOutput: EventEmitter<any> = new EventEmitter();
  //发射引导值
  @Output()
  addstepOutput: EventEmitter<any> = new EventEmitter();

  //清空表单
  @ViewChild('FormAdd') formElement: HTMLFormElement

  institutiondate: institutiondates = {};

  @Input() superiorAdd: any;

  @Input() superiorAddId: any;


  public createUserId: string;

  //datatype

  //清空选择框方法
  reset() {
    this.router.navigate(['user/management']);
    this.getTabList();
    this.formElement.reset();
    $('.fileinput-exists').click();
    setTimeout(() => {
      this.adddate.sex = 1;
      this.adddate.status = true;
      this.adddate.isActivate = true;
      this.adddate.isAutonym = true;
      //this.adddate.roleId = this.roledata[0].roleId;
    }, 300)
  }
  //所属角色
  public roledata: any;
  //初始化数据
  public adddate: any = {
    queryType: "1",
    roleId: '',
    roleName: "",
    userId: "",
    createUserId: this.createUserId,
    lastLoginDate: "",
    createDate: "",
    updatePasswordDate: "",
    institutionId: this.superiorAddId,
    parentId: this.superiorAddId,
    userName: "",
    displayName: "",
    password: "",
    email: "",
    registerSource: "",
    portrait: "",
    userFolder: "",
    status: true,
    isActivate: true,
    isAutonym: true,
    isSuper: null,
    activateKey: "",
    activateLastDate: "",
    realName: "",		  //真实姓名
    firstName: "",	  //姓
    lastName: "",		  //名
    identityCard: "", //身份证
    phone: "",		    //电话
    mobile: "",		    //手机
    sex: 1,		      //性别
    birthday: "",		  //生日	
    province: "",		  //省份
    city: "",	        //城市
    address: "",		  //地址
    qq: "",		        //qq号
    postCode: "",		  //邮编
    school: "",		    //学校   
    target: "user/person/"
  };

  submitAdd(val) {
    //console.log(val)
    // console.log(val.identityCard)
    //console.log(this.institutiondate.institutionId)
    this.adddate.institutionId = this.superiorAddId;
    this.adddate.createUserId = this.createUserId;
    val.status = Number(val.status)
    val.isActivate = Number(val.isActivate)
    val.isAutonym = Number(val.isAutonym)
    //转换时间格式
    val.birthday = this.server.formatDate(val.birthday);
    let formData = new FormData();
    for (let key in val) {
      formData.append(key, val[key] || "");
      val.institutionId = this.superiorAddId || '0';
      val.target = "user/person/";
    }
    //formData.append("imageinfo", $('#picID')[0].files[0] || '');

    let url = this.server.baseUrl + 'admin/pusers/add';
    let headers = new Headers({ 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryhdymHRIkeSu' });
    let options = new RequestOptions({ headers: headers });
    headers.delete("Content-Type");
    this.http.post(url, formData, options).toPromise().then((res: any) => {
      res = res.json();
      this.hintsService.messages(res.message,res.result_code);
      if (res.result_code == '0000') {
        $("#adminAdd").modal("hide");
        //console.log(res.message)
        this.addOutput.emit(res.result_code);
        this.reset();
        this.getTabList();
        //update
      }
    }).catch()
  }

  // 所属角色
  getTabList() {
    let url = this.server.baseUrl+'admin/roles/getRoleDropList';
    this.cudTableService.postRequest(url, {}).then((data: any) => {
      this.roledata = data.result;
      this.server.managementroleeeventEmit.emit(this.roledata)
       // console.log(this.roledata);
      if (this.roledata) {
        this.activerole(this.roledata);
        this.adddate.roleId = this.roledata[0].roleId;
      }
    }).catch();
  }

  //选中
  activerole(arry) {
    for (var i = 0; i < arry.length; i++) {
      if (arry[i].roleCode == "institutionSysUser") {
        this.adddate.roleId = arry[i].roleId;
      }
    }
  }

}

